﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Yunchang;
using UnityEngine.EventSystems;


namespace AutoChess
{
    /// <summary>
    /// 输入系统
    /// </summary>
    class FieldOperationHelper
    {
        #region static
        /// <summary>
        /// 是否击中中Unit
        /// </summary>
        /// <param name="screenPos"></param>
        public static ACGrid ClickGameFieldUnit(Vector2 screenPos)
        {
            Camera camera = null;
            if (AutoChessFieldViewCtr.Ins.SwitchCameraToUI)
                camera = CameraTools.Instance._uiCamera;
            else
                camera = AutoChessCamera.Ins.acCamera;
            if (!camera.gameObject.activeSelf)
                return null;

            ACGrid clicked = null;
            Ray ray = camera.ScreenPointToRay(Input.mousePosition);
            RaycastHit[] hits = Physics.RaycastAll(ray, 500);
            if (hits.Length > 0)
            {
                for (int i = 0; i < hits.Length; i++)
                {
                    var heroUnit = ActorManager.Instance.GetActor(hits[i].collider.gameObject);
                    if (heroUnit != null )
                    {
                        var heroGrid = heroUnit.Atrr.GetAtrribute<ACGrid>(ActorActionAttrDef.ACHero_GridData);
                        if (heroGrid != null)
                        {
                            clicked = heroGrid;
                            break;
                        }
                        else
                        {
                            BLogger.Assert(false);
                        }
                    }
                }
            }
            return clicked;
        }

        public static Vector3 GetDraggingModelPosition(Vector3 mousePosition, float rayLength)
        {
            var camera = AutoChessCamera.Ins.acCamera;
            var ray = camera.ScreenPointToRay(mousePosition);
            var hits = Physics.RaycastAll(ray, 500);
            Vector3 pos = Vector3.zero;
            foreach (var hit in hits)
            {
                if (hit.transform.name == "GroundCollider")
                {
                    pos = hit.point;
                }
            }
            var grid = AutoChessFieldViewCtr.Ins.SceneConfig.dragAreaGrid;
            var halfX = grid.Size.x / 2;
            var halfZ = grid.Size.y / 2;
            if (pos.x > halfX)
                pos.x = halfX;
            if (pos.x < -halfX)
                pos.x = -halfX;
            if (pos.z > halfZ)
                pos.z = halfZ;
            if (pos.z < -halfZ)
                pos.z = -halfZ;
            return pos;
        }
        #endregion

        #region MouseTouched

        public float RayLenght = 15f;

        private Vector3 mousePos;
        private bool isClickDown = false;
        private bool isDragging = false;

        // 预览用数据
        private ACHero selectedHeroUnit;
        private DragModelContainer dragContainer;

        // 操作用数据
        private ACGrid lastHitUnit;
        private ACGrid startHitUnit;
        private float holdTimer;

        public void OnPointerDown(PointerEventData eventData)
        {
            holdTimer = 0;
            ResetPreviewControlData();
            isClickDown = true;
            isDragging = false;
            mousePos = eventData.position;

            var hitUnit = FieldOperationHelper.ClickGameFieldUnit(eventData.position);
            lastHitUnit = hitUnit;
            startHitUnit = hitUnit;

            // 如果点击了角色,存储点击的角色信息
            if (hitUnit != null && hitUnit.heroUnit != null)
            {
                selectedHeroUnit = hitUnit.heroUnit;
            }

            // 发送点击消息 点击的格子信息 ,不判断是不是空的,让接受消息的地方自行处理
            EventManager.TriggerEvent<OpretionMsg>(CommonEvent.PUSH_GAMEFIELD_MSG, GameControlOperationMsg.NewClickDownUnitMsg(hitUnit));
        }

        public void OnPointerUp(PointerEventData eventData)
        {
            AutoChessManager.Ins.SetSqureEffect(false);
            if (isClickDown)
            {
                isClickDown = false;

                var hitUnit = FieldOperationHelper.ClickGameFieldUnit(eventData.position);

                // 移动到空位置或者没移动就重置预览,否则等待服务器消息
                if (hitUnit == null || hitUnit == startHitUnit || (hitUnit.GridType != GridType.FightGrid && hitUnit.GridType != GridType.PreChooseGrid))
                    ResetPreviewControlData();

                // 发送点击消息,之前点击的格子和当前松开位置的格子信息
                EventManager.TriggerEvent<OpretionMsg>(CommonEvent.PUSH_GAMEFIELD_MSG, GameControlOperationMsg.NewClickUpUnitMsg(startHitUnit, hitUnit));
            }
        }

        public void OnDrag(PointerEventData eventData)
        {
            if (isClickDown == true) // 拖拽
            {
                if (!AutoChessPlayerCtr.Ins.CurrentPlayer.IsSelfPlayer || AutoChessManager.Ins.GetCurrentState().GetStateType() == AutoChessModeState.ShowFightState)
                    return;
                if (AutoChessManager.Ins.GetCurrentState().GetStateType() == AutoChessModeState.ShowFightState)
                    return;
                if (startHitUnit == null || startHitUnit.GridType == GridType.EnemyGrid)
                    return;
                /*拖拽 长按
                *   处理预览信息
                */
                if (selectedHeroUnit != null)
                {
                    // 拖拽判定 
                    if (!isDragging && Vector2.Distance(mousePos.xy(), eventData.position) > 0.1f)
                    {
                        isDragging = true;
                        AutoChessManager.Ins.SetSqureEffect(true);
                        EventManager.TriggerEvent(CommonEvent.ON_SET_SHIP_GRID_PANEL, false);
                        AutoChessManager.DebugLog("Drag!", "操作");
                    }

                    var hitUnit = FieldOperationHelper.ClickGameFieldUnit(eventData.position);

                    // 长按判定
                    if (hitUnit == lastHitUnit)
                    {
                        holdTimer += Time.deltaTime;
                        if (holdTimer >= 2f)
                        {
                            EventManager.TriggerEvent<OpretionMsg>(CommonEvent.PUSH_GAMEFIELD_MSG, GameControlOperationMsg.NewHoldingUnitMsg(hitUnit));
                            isClickDown = false;
                            AutoChessManager.DebugLog("Hold!", "操作");
                            return;
                        }
                    }

                    if (isDragging)
                    {
                        holdTimer = 0f;

                        // 创建预览模型
                        if (dragContainer == null && AutoChessPlayerCtr.Ins.CurrentPlayer.IsSelfPlayer)
                        {
                            dragContainer = new DragModelContainer(selectedHeroUnit);
                        }

                        if (AutoChessPlayerCtr.Ins.CurrentPlayer.IsSelfPlayer)
                        {
                            // 更新预览模型
                            if (hitUnit != null && (hitUnit.GridType == GridType.FightGrid || hitUnit.GridType == GridType.PreChooseGrid))
                            {
                                dragContainer.UpdatePosition(hitUnit.Position);
                                if(hitUnit.GridType == GridType.FightGrid)
                                    dragContainer.UpdateRotation(90);
                                else
                                    dragContainer.UpdateRotation(180);
                                if (startHitUnit != null && startHitUnit.GridType != GridType.ShopGrid)
                                    AutoChessManager.Ins.ChangeMeshPos(true, startHitUnit.Position, hitUnit.Position);
                                else
                                    AutoChessManager.Ins.ChangeMeshPos(false, Vector3.zero, Vector3.zero);
                            }
                            else
                            {
                                dragContainer.UpdatePosition(FieldOperationHelper.GetDraggingModelPosition(eventData.position, RayLenght));
                                dragContainer.UpdateRotation(180);
                                AutoChessManager.Ins.ChangeMeshPos(false, Vector3.zero, Vector3.zero);
                            }

                            // 更新切换高亮显示的格子信息
                            if (lastHitUnit != hitUnit)
                            {
                                if (hitUnit != null && (hitUnit.GridType == GridType.FightGrid || hitUnit.GridType == GridType.PreChooseGrid))
                                {
                                    EventManager.TriggerEvent<OpretionMsg>(CommonEvent.PUSH_GAMEFIELD_MSG, GridOpretionMsg.NewHighLightGridMsg(hitUnit));
                                }
                                else
                                {
                                    EventManager.TriggerEvent<OpretionMsg>(CommonEvent.PUSH_GAMEFIELD_MSG, GridOpretionMsg.NewHighLightGridMsg(null));
                                }
                                // 切换高亮显示
                                lastHitUnit = hitUnit;
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 重置预览操作
        /// </summary>
        public void ResetPreviewControlData()
        {
            if (dragContainer != null)
            {
                dragContainer.Release();
                dragContainer = null;
            }
            selectedHeroUnit = null;
            AutoChessManager.Ins.ChangeMeshPos(false, Vector3.zero, Vector3.zero);
            EventManager.TriggerEvent<OpretionMsg>(CommonEvent.PUSH_GAMEFIELD_MSG, GridOpretionMsg.NewHighLightGridMsg(null));
        }
        #endregion
    }
}
